// 乾坤全局通信
import { BASE_VITE_TS_KEY } from '@/config';
import { useUserStore, type User } from '@glz/utils'
import { initGlobalState, type MicroAppStateActions } from 'qiankun'

// const initState = {
//   // 这里写初始化数据
//   mainMsg: 0,
//   app1Msg: 0,
//   app2Msg: 0,
//   useUserStore: useUserStore()
// }

// 共享全局主题和语言
export interface GlobalState {
  theme: "light" | "dark";
  language: "en" | "zn";
  useUserStore: User,
  user:{}
 }
 
 export const globalState: GlobalState = {
  theme: "light",
  language: "zn",
  useUserStore: {} as User,
  user:{}
 };
 
const actions:MicroAppStateActions = initGlobalState(globalState)


//在当前应用监听全局状态，有变更触发 callback，fireImmediately = true 立即触发 callback
actions.onGlobalStateChange((state, prevState) => {
  // state: 变更后的状态; prevState 变更前的状态
  console.log(prevState, '主应用变更前')
  console.log(state, '主应用变更后')

  const store_user = useUserStore(BASE_VITE_TS_KEY)
  store_user.user = state.useUserStore

})

// 按一级属性设置全局状态，微应用中只能修改已存在的一级属性
//actions.setGlobalState(initState);
// 移除当前应用的状态监听，微应用 umount 时会默认调用
//actions.offGlobalStateChange();

export default actions